package com.example.myapplication;

/**
 * Created by Yi on 13-8-22.
 */

import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;

/*
* A warp up class for HTTP operations
* ALl http request must be called in the main thread(UI thread)
* The async func is warpped up inside the object
* */
public class HttpHandler
{
    private ArrayList<HTTPResultListener> listeners;

    public void addListener(HTTPResultListener listener){
        listeners.add(listener);
    }

    public void removeListener(HTTPResultListener listener){
        if (listeners == null) return;
        listeners.remove(listener);
    }

    private void fireGetResult(String result)
    {
        Iterator<HTTPResultListener> iter = listeners.iterator();
        while (iter.hasNext()){
            HTTPResultListener listener = (HTTPResultListener)iter.next();
            HTTPResultEventObj obj = new HTTPResultEventObj(this, result);
            listener.onGetResult(obj);
        }
    }

    public void requestAsync(String url){
        new requestAsyncImpl().execute(url);
    }

    private class requestAsyncImpl extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... strings) {
            try {
                return requestURL(strings[0]);
            }catch ( IOException ex ){
                Log.d(Global.DEBUG_TAG, "Unable to retrieve http contents");
            }
            return null;
        }

        // this is the func call back by main thread (UI thread)
        @Override
        protected void onPostExecute(String result){
            // notify subscribers here
            fireGetResult(result);
        }
    }

    private String requestURL(String url) throws IOException {
        InputStream is = null;
        try {
            URL connUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)connUrl.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(10000);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);

            conn.connect();
            int response = conn.getResponseCode();
            Log.d(Global.DEBUG_TAG, "The response is:" + response);
            is = conn.getInputStream();

            String contentAsString = StrUtil.readFromStream(is);
            return  contentAsString;
        }
        finally {
            if (is!=null) is.close();
        }
    }
}
